package linklist;

/**
 * @className: linklist.LeetCode_24
 * @Description: ...
 * @author: kunkun
 * @date: 2025/3/19 22:01
 */
public class LeetCode_24 {

    public class ListNode {
       int val;
       ListNode next;
       ListNode() {}
       ListNode(int val) { this.val = val; }
       ListNode(int val, ListNode next) { this.val = val; this.next = next; }
   }

    public ListNode swapPairs(ListNode head) {
        //1. 计算长度
        int length = 0;
        ListNode temp = head;
        while (temp!=null){
            length++;
            temp=temp.next;
        }
        int count = length/2;

        //2. 定义变量
        ListNode before = new ListNode(),after = head,result = before;
        temp = head;
        before.next = head;

        //3. 循环
        for (int i = 0; i < count; i++) {
            //3.1 after后移
            after=after.next.next;
            //3.2 交换
            before = exchange(temp,before,after);
            //3.3 temp后移
            temp = before.next;
        }

        return result;

    }

    private ListNode exchange(ListNode head, ListNode before, ListNode after) {
        ListNode temp = head.next;
        before.next = temp;
        temp.next = head;
        head.next = after;
        return head;
    }


}
